package vn.edu.saigontech.ncms.web.user;

import vn.edu.saigontech.ncms.model.user.Site;
import vn.edu.saigontech.ncms.model.user.User;
import vn.edu.saigontech.ncms.service.SiteService;
import vn.edu.saigontech.ncms.service.UserService;
import vn.edu.saigontech.ncms.util.Checker;
import vn.edu.saigontech.ncms.web.BaseAction;

@SuppressWarnings("serial")
public class AuthenticationAction extends BaseAction {
	
	private String username;
	private String password;
	private Long siteId;
	
	public String showLogin() {
		return SUCCESS;
	}
	
	public String login() throws Exception {
		User user = UserService.INSTANCE.login(this.username, this.password);
		if(Checker.isNull(user)) {
			REQUEST().setAttribute("error", this.i18n("login.invalid"));
			return INPUT;
		}
		if(!user.isActive()) {
			REQUEST().setAttribute("error", this.i18n("login.inactive"));
			return INPUT;
		}
		Site site = SiteService.INSTANCE.findById(this.siteId);
		if(!user.getSites().contains(site)) {
			System.out.println("problem");
			REQUEST().setAttribute("error", this.i18n("login.wrongsite"));
			return INPUT;
		}
		SESSION().setAttribute("user", user);
		SESSION().setAttribute("site", site);
		RESPONSE().sendRedirect(site.getPage());
		
		this.addLoggingDetail(BaseAction.LOGIN, "logging.log.in");
		return NONE;
	}
	
	public String logout() {
		SESSION().invalidate();
		return SUCCESS;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Long getSiteId() {
		return siteId;
	}

	public void setSiteId(Long siteId) {
		this.siteId = siteId;
	}
}